package com.xfg.domain.strategy.service.raffle;

import com.xfg.domain.strategy.model.entity.RaffleFactorEntity;
import com.xfg.domain.strategy.model.entity.RuleActionEntity;
import com.xfg.domain.strategy.model.entity.RuleMatterEntity;
import com.xfg.domain.strategy.model.valobj.RuleLogicCheckTypeV0;
import com.xfg.domain.strategy.model.valobj.RuleTreeVO;
import com.xfg.domain.strategy.model.valobj.StrategyAwardRuleModelVO;
import com.xfg.domain.strategy.repository.IStrategyRepository;
import com.xfg.domain.strategy.service.AbstractRaffleStrategy;
import com.xfg.domain.strategy.service.armory.IStrategyDispatch;
import com.xfg.domain.strategy.service.rule.chain.ILogicChain;
import com.xfg.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import com.xfg.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import com.xfg.domain.strategy.service.rule.tree.factory.engine.IDecisionTreeEngine;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DefaultRaffleStrategy  extends AbstractRaffleStrategy {


    public DefaultRaffleStrategy(IStrategyRepository repository, IStrategyDispatch strategyDispatch, DefaultChainFactory defaultChainFactory, DefaultTreeFactory defaultTreeFactory) {
        super(repository, strategyDispatch, defaultChainFactory, defaultTreeFactory);
    }

    @Override
    public DefaultChainFactory.StrategyAwardVO raffleLogicChain(String userId, Long strategyId) {
        ILogicChain logicChain = defaultChainFactory.openLogicChain(strategyId);
        return logicChain.logic(userId, strategyId);

    }

    @Override
    public DefaultTreeFactory.StrategyAwardVO raffleLogicTree(String userId, Long strategyId, Integer awardId) {
        StrategyAwardRuleModelVO strategyAwardRuleModelVO = repository.queryStrategyAwardRuleModelVO(strategyId, awardId);
        if (null == strategyAwardRuleModelVO) {
            return DefaultTreeFactory.StrategyAwardVO.builder().awardId(awardId).build();
        }
        RuleTreeVO ruleTreeVO = repository.queryRuleTreeVOByTreeId(strategyAwardRuleModelVO.getRuleModels());
        if (null == ruleTreeVO) {
            throw new RuntimeException("存在抽奖策略配置的规则模型 Key，未在库表 rule_tree、rule_tree_node、rule_tree_line 配置对应的规则树信息 " + strategyAwardRuleModelVO.getRuleModels());
        }
        IDecisionTreeEngine treeEngine = defaultTreeFactory.openLogicTree(ruleTreeVO);
        return treeEngine.process(userId, strategyId, awardId);

    }

//    @Override
//    protected RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> doCheckRaffleBeforeLogic(RaffleFactorEntity raffleFactorEntity, String... logics) {
//        //获取所有可用的规则过滤器，构建一个以规则模型为键、过滤器为值的映射表，用于后续按规则模型执行对应的校验逻辑。
//        Map<String, ILogicFilter<RuleActionEntity.RaffleBeforeEntity>> logicFilterGroup = logicFactory.openLogicFilter();
//        // 黑名单规则优先过滤
//        // 首先通过logicFactory获取所有可用的规则过滤器；然后从传入的规则列表中筛选出包含“黑名单”规则的项，优先处理黑名单逻辑。
//        String ruleBackList = Arrays.stream(logics)
//                .filter(str -> str.contains(DefaultLogicFactory.LogicModel.RULE_BLACKLIST.getCode()))
//                .findFirst()
//                .orElse(null);
//        //黑名单规则处理：如果 ruleBackList 不为空，其实就是证明黑名单不是空的，表示需要执行黑名单校验。
//        if (StringUtils.isNotBlank(ruleBackList)) {
//            ILogicFilter<RuleActionEntity.RaffleBeforeEntity> logicFilter = logicFilterGroup.get(DefaultLogicFactory.LogicModel.RULE_BLACKLIST.getCode());
//            //构建规则实体：创建 RuleMatterEntity 并设置用户ID、奖品ID、策略ID和规则模型（黑名单）。
//            //物料实体类的主要作用:作为规则校验的上下文载体
//            RuleMatterEntity ruleMatterEntity = new RuleMatterEntity();
//            ruleMatterEntity.setUserId(raffleFactorEntity.getUserId());
//            ruleMatterEntity.setAwardId(ruleMatterEntity.getAwardId());
//            ruleMatterEntity.setStrategyId(raffleFactorEntity.getStrategyId());
//            //明确告诉过滤器当前需要处理的是黑名单规则
//            ruleMatterEntity.setRuleModel(DefaultLogicFactory.LogicModel.RULE_BLACKLIST.getCode());
//            //执行过滤：调用 logicFilter.filter() 执行黑名单逻辑判断。
//            RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> ruleActionEntity = logicFilter.filter(ruleMatterEntity);
//            //返回结果：若校验不通过（非允许状态），直接返回 ruleActionEntity，阻止后续流程。
//            //确定是黑名单用户时直接返回黑名单实体
//            if (!RuleLogicCheckTypeV0.ALLOW.getCode().equals(ruleActionEntity.getCode())) {
//                return ruleActionEntity;
//            }
//        }
//        // 顺序过滤剩余规则
//        //ruleList：从传入的 logics 中排除黑名单规则，仅保留其他需要校验的规则。
//        List<String> ruleList = Arrays.stream(logics)
//                .filter(s -> !s.equals(DefaultLogicFactory.LogicModel.RULE_BLACKLIST.getCode()))
//                .collect(Collectors.toList());
//
//        RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> ruleActionEntity = null;
//        //循环处理：对每个规则模型依次执行校验，确保按顺序进行。
//        for (String ruleModel : ruleList) {
//            ILogicFilter<RuleActionEntity.RaffleBeforeEntity> logicFilter = logicFilterGroup.get(ruleModel);
//            //创建 RuleMatterEntity 并填充用户、奖品、策略和规则信息。
//            RuleMatterEntity ruleMatterEntity = new RuleMatterEntity();
//            ruleMatterEntity.setUserId(raffleFactorEntity.getUserId());
//            ruleMatterEntity.setAwardId(ruleMatterEntity.getAwardId());
//            ruleMatterEntity.setStrategyId(raffleFactorEntity.getStrategyId());
//            ruleMatterEntity.setRuleModel(ruleModel);
//            //执行过滤：调用 logicFilter.filter() 执行具体规则逻辑。
//            ruleActionEntity = logicFilter.filter(ruleMatterEntity);
//            // 非放行结果则顺序过滤
//            //输出当前规则校验的结果，便于调试和追踪。
//            log.info("抽奖前规则过滤 userId: {} ruleModel: {} code: {} info: {}", raffleFactorEntity.getUserId(), ruleModel, ruleActionEntity.getCode(), ruleActionEntity.getInfo());
//            if (!RuleLogicCheckTypeV0.ALLOW.getCode().equals(ruleActionEntity.getCode())) {
//                //提前返回：若任一规则校验不通过（非 ALLOW 状态），立即返回结果，阻止后续流程。
//                return ruleActionEntity;
//            }
//        }
//        //最终返回：所有规则校验通过后，返回最后一个规则的结果。
//        return ruleActionEntity;
//
//    }
}
